import axios from 'axios'
import { Message, Loading } from 'element-ui'
import qs from 'qs'

const instance = axios.create({
    timeout: 10000
})

// var count = 0;
var loadingInstance = null;

//请求前拦截
instance.interceptors.request.use(config => {
    // console.log(process.env.NODE_ENV)
    // target: '.content-wrapper'
    loadingInstance = Loading.service({
        fullscreen: true,
        text: '拼命加载中...',
        background: 'rgba(0, 0, 0, 0.8)'
    })
    // console.log(config)
    const token = localStorage.getItem('token')
    if (config.method === 'post') {
        if (token) {
            const data = token
            config.headers.common['Authorization'] = "BasicAuth " + data
            // console.log(token)
            console.log(config)
        }
        // config.data = qs.stringify(config.data, { allowDots: true, arrayFormat: 'repeat' })
    } 
    else if (config.method === 'get') {
        if (token) {
            const getdata = token
            console.log(getdata)
            config.headers.common['Authorization'] = "BasicAuth " + getdata
        }
        // config.url += '?' + qs.stringify(config.params, { arrayFormat: 'repeat' })
        // console.log(config.params)
        // console.log(config)
    }
    return config
}, err => {
    // count--;
    // if(count == 0) {
    loadingInstance.close()
    Message.error({ message: '请求超时!' })
    return Promise.reject(err)
    // }
    // return Promise.reject(err)
})

//返回结果后
instance.interceptors.response.use(result => {
    loadingInstance.close()
    console.log(result)
    const data = result.data
    if (data.StatusCode != 200) {
        Message.error({
            message: data.Message
        })
    }
    return data
}, err => {
    loadingInstance.close()
    return Promise.reject(err)
})
export default instance